import { debug } from '@/components/toast/debug'
import { AuthPayload, LoginInput, useLoginMutation } from '@/generated/graphql'
import { Route } from '@/router'
import { useUserStore } from '@/stores/auth'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const checkUsername = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('username is required!')
  }
  return Promise.resolve()
}

const checkPassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('password i required!')
  }
  return Promise.resolve()
}

export const loginRules: Record<string, Rule[]> = {
  username: [{ required: true, validator: checkUsername, trigger: 'change' }],
  pass: [{ required: true, trigger: 'change', validator: checkPassword }],
}

export const useLoginAction = () => {
  const router = useRouter()
  const { executeMutation: login } = useLoginMutation()

  const { t } = useI18n()

  const userStore = useUserStore()

  const submit = (values: any) => {
    const { username, pass } = values
    login({ username, password: pass } as LoginInput)
      .then(({ data, error }) => {
        if (error) {
          debug(error.message)
          message.error(error.message, 2)
          return false
        }
        if (data) {
          //检查用户是否启用 enabled
          if (!data.login.user?.enabled) {
            message.warning('This account has been disabled', 2.5, () => {
              router.replace({ name: Route.LOGIN })
            })
            return
          }
          //检查是否禁止登录
          if (dayjs().isAfter(dayjs(data.login.user.expiredAt))) {
            message.warning('This account has been disabled!', 2.5, () => {
              router.replace({ name: Route.LOGIN })
            })
            return
          }
          //写入本地session
          userStore.M_setAuthState(data.login as AuthPayload)
          message.success(t('toast.login_success'))
          router.push({
            name: Route.ROOT,
          })
        }
      })
      .catch(console.error)
  }
  return { submit }
}
